const { join } = require('path');

/************* *TODO:配置信息,数据对应的Url*************/
const dataUrl = /^\/base/;
const moduleUrl = /^\/modules\/binge/;
const modulePort = 9001;
const container = join(__dirname, '../container');//容器代码
const proxyData = [
  "/base/sys/user/login","/base/sys/user/info","/base/msg/channel/info/list",
  "/base/sys/user/token","/base/sys/user/logout","/base/today","/base/table","/base/back"
];//联调请求数据
const proxyUrl = "http://localhost:3000";//联调对应地址
const mockFiles = [
  // "filter/LoginController.json", "filter/MsgController.json", "data/test/TestController.json"
];//mock数据文件
const proxyReq = require(join(__dirname,'../proxy/proxy.js'));

/**************************************************/

var express = require('express')
var app = express();
var httpProxy = require('http-proxy');
const mime = require('mime');
const fs = require('fs');


// 新建一个代理 Proxy Server 对象  
var proxy = httpProxy.createProxyServer({
  secure: true,
  changeOrigin: true,
  ws: true
});
const MockData = {};
//加载mock文件数据
mockFiles.forEach(n => {
  const mock = require(join(__dirname, n));
  mock.forEach(m => {
    if (m.method == null || m.method == "") {
      MockData["post" + m.url] = m.result;
      MockData["get" + m.url] = m.result;
    } else {
      MockData[m.method.toUpperCase() + m.url] = m.result;
    }
  })
});

app.all(/^\/(?!socket)/, function (req, res) {
  let url = req.url.replace(/\?[\s\S]+$/, '');
  url = dataUrl.test(url) || /\.[\w]+($|\?)/.test(url) ? url : url + 'index.html';

  if(proxyReq[url]!=null){
    res.writeHeader(200, {
      'content-type': mime.getType(req.url) + ';charset="utf-8"'
    });
    const readerstream = fs.createReadStream(join(__dirname,'../proxy/req',proxyReq[url] ));
    readerstream.pipe(res);
    return;
  }


  if (dataUrl.test(url)) {//数据请求,有联调的,可以从这里转过去
    if (proxyData.find(n => url == n)) {//远程代理数据
      proxy.web(req, res, { target: proxyUrl }, (err) => {
        console.log(err);
        console.info('请求有异常');
      });
      return;
    }
    const data = MockData[req.method + url.replace(dataUrl, '')];
    //本地mock数据
    if (data == null) {
      res.writeHeader(404, {
        'content-type': 'application/json;charset="utf-8"'
      });
      res.write('{"errorNo":-1,"errorMsg":"404"}');
      res.end();
      return;
    }
    res.writeHeader(200, {
      'content-type': 'application/json;charset="utf-8"'
    });
    res.write(JSON.stringify(data));
    res.end();
    return;
  } else if (moduleUrl.test(req.url)) {
    proxy.web(req, res, { target: "http://localhost:" + modulePort }, (err) => {
      console.log(err);
      console.info('请求有异常');
    });
    return;
  }

  if (!fs.existsSync(join(container, url))) {
    res.writeHeader(404, {
      'content-type': mime.getType(req.url) + ';charset="utf-8"'
    });
    res.end();
    return;
  }
  res.writeHeader(200, {
    'content-type': mime.getType(req.url) + ';charset="utf-8"'
  });
  const readerstream = fs.createReadStream(join(container, url));
  readerstream.pipe(res);
})

var http = require('http').Server(app);
var io = require('socket.io')(http);

io.on('connection', function (socket) {
  console.log('新用户登录');
})


const server = http.listen(80, function () {
  console.log("应用实例，访问地址为 http://localhost")
});